class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k)
    {
        if (k == 0)return 0;
        int ret = 0;
        int left = 0, right = 0, n = s.size();
        unordered_map<char, int> map;

        while (right < n)
        {
            map[s[right++]]++;
            while (map.size() == k + 1)
            {
                map[s[left]]--;
                if (map[s[left]] == 0) map.erase(s[left]);
                left++;
            }
            ret = max(ret, right - left);

        }
        return ret;
    }
};